//
//  LivestockPropertyHeaderView.m
//  Trackit
//
//  Created by yaodaobin on 2017/4/17.
//  Copyright © 2017年 yaodaobin. All rights reserved.
//

#import "LivestockPropertyHeaderView.h"
#import "PropertyCell.h"
#import "PropertyItem.h"
#import "PropertyPickCell.h"
#import "PropertyGenderCell.h"

@interface LivestockPropertyHeaderView() <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *totalArray;
@end


@implementation LivestockPropertyHeaderView

#pragma mark - Init
- (void)awakeFromNib {
    [super awakeFromNib];
    [self initUI];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initUI];
    }
    return self;
}

- (void)initUI {
    self.totalArray = [NSMutableArray array];
    [self addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    [self.tableView registerClass:[PropertyCell class] forCellReuseIdentifier:NSStringFromClass([PropertyCell class])];
    [self.tableView registerClass:[PropertyPickCell class] forCellReuseIdentifier:NSStringFromClass([PropertyPickCell class])];
    [self.tableView registerClass:[PropertyGenderCell class] forCellReuseIdentifier:NSStringFromClass([PropertyGenderCell class])];

}

#pragma Setter
- (void)setTaskDetail:(TaskDetailModel *)taskDetail {
    _taskDetail = taskDetail;
    NSArray *tempKeyArray = [TaskListModel getPropertyKeyArray:self.taskDetail.collectDataType];
    NSArray *tempValueArray = [TaskListModel getPropertyValueArray:self.taskDetail.collectDataType];
    
    if (self.totalArray.count > 0) {
        [self.totalArray removeAllObjects];
    }
    for (int i = 0; i < tempKeyArray.count; i++) {
        NSArray *keys = tempKeyArray[i];
        NSArray *values = tempValueArray[i];
        NSMutableArray *addArray = [NSMutableArray array];
        for (int i = 0; i < keys.count; i++) {
            PropertyItem *item = [[PropertyItem alloc] init];
            item.inputTitle = keys[i][0];
            item.itemKey = values[i];
            item.keyboard = [keys[i][1] integerValue];
            item.showArrow = [keys[i][2] boolValue];
            item.propertyType = [keys[i][3] integerValue];
            [addArray addObject:item];
        }
        [self.totalArray addObject:addArray];
    }
    [self reloadData];
}

#pragma mark - Getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView.scrollEnabled = NO;
    }
    return _tableView;
}

#pragma mark - Public
- (BOOL)validateFillAll {
    BOOL result = YES;
    BOOL isIDCell = NO;
    for (int i = 0; i < self.totalArray.count; i++) {
        NSArray *array = self.totalArray[i];
        for (int j = 0; j < array.count; j++) {
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:j inSection:i]];
            if ([cell isKindOfClass:[PropertyCell class]]) {
                if ([((PropertyCell *)cell).titleLabel.text isEqualToString:@"确权证号"]) {
                    continue;
                }
                if ([((PropertyCell *)cell).titleLabel.text isEqualToString:@"身份证号"]) {
                    isIDCell = YES;
                    NSString *idString = ((PropertyCell *)cell).textField.text;
                    if (idString.length != 18 || ![CommonFunction validateIdCard:idString]) {
                        result = NO;
                        break;
                    }
                }
                if (((PropertyCell *)cell).textField.text.length == 0) {
                    result = NO;
                    break;
                }
            } else if ([cell isKindOfClass:[PropertyPickCell class]]) {
                if ([((PropertyPickCell *)cell).contentLabel.text isEqualToString:@"请选择"]) {
                    result = NO;
                    break;
                }
            }
        }
    }
    
    if (!result) {
        if (isIDCell) {
            [TKUtil showMessage:@"身份证号码不正确"];
        } else {
            [TKUtil showMessage:@"还有未填选项"];
        }
    }
    return result;
}

- (NSMutableDictionary *)getInfo {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    for (int i = 0; i < self.totalArray.count; i++) {
        NSArray *array = self.totalArray[i];
        for (int j = 0; j < array.count; j++) {
            PropertyItem *item = array[j];
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:j inSection:i]];
            if ([cell isKindOfClass:[PropertyCell class]]) {
                item.itemValue = ((PropertyCell *)cell).textField.text;
            } else if ([cell isKindOfClass:[PropertyPickCell class]]) {
                item.itemValue = ((PropertyPickCell *)cell).contentLabel.text;
            } else if ([cell isKindOfClass:[PropertyGenderCell class]]) {
                item.itemValue = [((PropertyGenderCell *)cell) getGenderString];
            }
        }
    }
    for (int i = 0; i < self.totalArray.count; i++) {
        NSArray *array = self.totalArray[i];
        for (int j = 0; j < array.count; j++) {
            PropertyItem *item = array[j];
            if ([item.inputTitle isEqualToString:@"州县乡"]) {
                NSArray *ar = [item.itemValue componentsSeparatedByString:@" "];
                if (ar.count > 2) {
                    [dic safeSetObject:ar[0] forKey:@"City"];
                    [dic safeSetObject:ar[1] forKey:@"County"];
                    [dic safeSetObject:ar[2] forKey:@"Township"];
                }
            } else {
                [dic safeSetObject:item.itemValue forKey:item.itemKey];
            }
        }
    }
    return dic;
}

- (void)resignFirstResponder {
    for (UITableViewCell *cell in self.tableView.visibleCells) {
        if ([cell isKindOfClass:[PropertyCell class]]) {
            [((PropertyCell *)cell).textField resignFirstResponder];
        }
    }
}

- (CGFloat)currentOffset {
    NSUInteger index = 0;
    CGFloat offset = 0;
    for (int i = 0; i < self.tableView.visibleCells.count; i++) {
        UITableViewCell *cell = self.tableView.visibleCells[i];
        if ([cell isKindOfClass:[PropertyCell class]]) {
            if ([((PropertyCell *)cell).textField isFirstResponder]) {
                index = i;
                offset = cell.frame.origin.y;
                break;
            }
        } else if ([cell isKindOfClass:[PropertyPickCell class]]) {
            if ([((PropertyPickCell *)cell).locateView isAppeared]) {
                index = i;
                offset = cell.frame.origin.y;
                break;
            }
        }
    }

    return offset;
}

#pragma mark - Private
- (void)reloadData {
    [self.tableView reloadData];
}

#pragma mark - UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.totalArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *array = [self.totalArray safeObjectAtIndex:section];
    return array.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.width, 10)];
    view.backgroundColor = [UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1.0f];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PropertyItem *item = self.totalArray[indexPath.section][indexPath.row];
    switch (item.propertyType) {
        case PropertyTypeDefault:
        {
            PropertyCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PropertyCell class])];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.currentIndex = indexPath.row;
            cell.accessoryType = item.showArrow ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
            cell.item = item;
            return cell;
        }
        case PropertyTypePicker:
        {
            kWeakSelf
            PropertyPickCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PropertyPickCell class])];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = item.showArrow ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
            cell.taskDetail = self.taskDetail;
            cell.item = item;
            cell.selectedAreaBlock = ^{
                [weakSelf.tableView reloadData];
            };
            
            cell.resignKeyboardBlock = ^{
                [weakSelf resignFirstResponder];
            };
            return cell;

        }
        case PropertyTypeOther:
        {
            PropertyGenderCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PropertyGenderCell class])];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = item.showArrow ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
            cell.item = item;
            return cell;
        }
            
    }
}

@end

